/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2021并保留所有权利。
 * Copyright 2021, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.redis.test;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.druid.wall.violation.ErrorCode;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BaseResult {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedisUtil redisUtil;
    public ResponseResult getCouponCode(@RequestParam String param) {
        log.info("CouponManageController getCouponCodebegin");
        log.info("CouponManageController getCouponCode入参param;"+param);
        String lockValue = String.valueOf(System.currentTimeMillis() + 5000);
        String str;
        if("01".equals(param)){
            log.info("查询优惠券编码code");
            str = "COUPONCODE";
        }else {
            log.info("查询定向发券编码code");
            str = "SENDCOUPONCODE";
        }
        try {
            Boolean flag;
            Integer couponCode;
            while (true) {
                flag = redisUtil.getlock(str + "_temp", lockValue);
                if (!flag) {
                    log.info("当前有进程在获取券编码");
                } else {
                    if (null != redisTemplate.opsForValue().get(str)) {
                        couponCode = ((Integer) redisTemplate.opsForValue().get(str) + 1);
                        redisTemplate.opsForValue().set(str, (Integer) redisTemplate.opsForValue().get(str) + 1);
                    } else {
                        redisTemplate.opsForValue().set(str, 100001);
                        couponCode = 100001;
                    }
                    break;
                }
            }
            log.info("券编码code为" + couponCode);
            ResponseResult ResponseResult = new ResponseResult(ResponseCode.SUCCESS.getCode(),"","");//ResponseResult.success(new ArrayList<>());
            redisUtil.unlock(str + "_temp", lockValue);
            List<String> result = new ArrayList<>();
            result.add(couponCode.toString());
            ResponseResult.setData(result);
            return ResponseResult;
        } catch (Exception e) {
            redisUtil.unlock(str + "_temp", lockValue);
            log.error("CouponManageController getCouponCode error", e.getMessage(), e);
            return new ResponseResult(ResponseCode.SUCCESS.hashCode(),"","");
        }
    }

}
